package com.finalab.yueqiu.service.text;

import com.finalab.yueqiu.constant.TextType;
import com.qcloud.cos.utils.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author 莉安
 */
@Service
public class TextFilterServiceImpl implements TextFilterService{


    private static final String[] REPLACE_CHARS = { "<",">", "\"", " "};
    private static final String[] REPLACE_STRING = {"&quot;", "&lt;", "&gt;","&nbsp;", "&amp;"};
    /**
     * 这里不知道怎么替换掉客户端没有检查的&
     * @param text
     * @return
     */
    private boolean checkChar(String text){

        for(int i = 0;i < REPLACE_CHARS.length;i++){
            if(text.contains(REPLACE_CHARS[i])){
                return false;
            }
        }
        return true;
    }
    private String replaceChar(String text){
        return text.replaceAll(REPLACE_STRING[0], "\"")
                .replaceAll(REPLACE_STRING[1], "<")
                .replaceAll(REPLACE_STRING[2], ">")
                .replaceAll(REPLACE_STRING[3], " ")
                .replaceAll(REPLACE_STRING[4], "&");
    }

    @Override
    public String getFilterString(String text, TextType textType){
        if(StringUtils.isNullOrEmpty(text)){
            return text;
        }
        if(!checkChar(text)){
            return null;
        }
        switch (textType){
            case USER_NAME:
            case POST_TITLE:
            case POST_CONTENT:
            default:break;
        }
        text = replaceChar(text);
        return text;
    }
}
